package com.yuyang.wifi.activitys.web;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yuyang.wifi.R;
import com.yuyang.wifi.base.AppManager;
import com.yuyang.wifi.base.BaseActivity;
import com.yuyang.wifi.base.Constants;
import com.yuyang.wifi.utils.MPermissionUtils;
import com.yuyang.wifi.utils.ToastUtils;
import com.umeng.analytics.MobclickAgent;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by mej
 * on 2020/9/7
 */
public class MyWebView extends BaseActivity {

    private WebView mWebView;
    private String mTitle;

    @BindView(R.id.centre_title)
    TextView centreTitle;
    @BindView(R.id.fragment)
    FrameLayout framelayout;


    @Override
    protected void initActionBar() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_my_webview;
    }

    @Override
    protected void initContentView() {
        initWebView();
        //requestCameraPermission();
    }

    //请求相机权限
    private void requestCameraPermission() {
        MPermissionUtils.requestPermissionsResult(this, Constants.PERMISSION_CAMERA, Constants.MULTI_PERMISSIONS
                , new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        initWebView();
                    }

                    @Override
                    public void onPermissionDenied() {
                        ToastUtils.showShortToast(MyWebView.this, "当前权限务必开启,否则影响部分功能使用");
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void initWebView() {
        mWebView = new WebView(getApplicationContext());
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.addJavascriptInterface(new JavaScriptInterface(this), "android");
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // ToastUtils.showShortToast(MyWebView.this, "页面加载完成");
                Log.e("mywebview", "url===: " + url);
                dismissDialog();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                dismissDialog();
                mWebView.setVisibility(View.GONE);
                ToastUtils.showShortToast(getApplicationContext(), "请求失败，请退出重试");

            }

            //            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return true;
//            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (URLUtil.isNetworkUrl(url)) {
                    if (view != null) {
                        view.loadUrl(url);
                    }
                    return true;
                } else {
                    try {
                        Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }

//                if (url.startsWith("weixin://wap/pay?")) {
//
//                    Intent intent = new Intent();
//
//                    intent.setAction(Intent.ACTION_VIEW);
//
//                    intent.setData(Uri.parse(url));
//
//                    startActivity(intent);
//                    return true;
//                } else if (url.startsWith("alipays://platformapi/startApp")) {
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_VIEW);
//                    intent.setData(Uri.parse(url));
//                    startActivity(intent);
//                    return true;
//                }

               // return super.shouldOverrideUrlLoading(view, url);

            }
        });
        WebChromeClient wvcc = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);

                Log.e("mywebview", "title===: " + title);

                mTitle = title;

                //title 就是网页的title
                if (title.equals("努力载入中..") || title.equals("DIY商城") || title.equals("matrix." +
                        "venomlipstick.cn/?channelId=647") || mWebView.getUrl().
                        equals("http://matrix.venomlipstick.cn/?channelId=648&sourceId=648")) {
                    centreTitle.setText("鲨鱼赚钱极速版");
                } else {
                    centreTitle.setText(title);
                }
            }
        };
        mWebView.setWebChromeClient(wvcc);
        // synCookies(this, url);
        framelayout.addView(mWebView);
        mWebView.loadUrl("http://matrix.venomlipstick.cn/?channelId=648&sourceId=648");
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        if (mWebView.canGoBack()) {
            if (mWebView.getUrl().equals("http://matrix.venomlipstick.cn/?channelId=648&sourceId=648")) {
                super.onBackPressed();
            } else {
                mWebView.goBack();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            if (mWebView.getUrl().equals("http://matrix.venomlipstick.cn/?channelId=648&sourceId=648")) {
                finish();
            } else {
                if (mTitle.equals("努力载入中..")) {
                    finish();
                } else {
                    mWebView.goBack();
                }
            }
        } else {
            finish();
        }
    }

    //手机连续按返回键两次的间隔时间
    private long mExitTime;

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            MobclickAgent.onKillProcess(this);//程序退出时，用于保存统计数据的API。
            ToastUtils.cancelToast();
            finish();
            AppManager.getInstance().finishAllActivity();
        }
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.stopLoading();
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.removeAllViews();
            mWebView.destroy();
        }
        super.onDestroy();
    }

}
